/**
 * licenses
 *
 */

package com.openjawtech.xscraper.flights.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.AnnotationConfiguration;
import java.util.Properties;

/**
 * <p>a factory used to create and manage the hibernate session
 *
 * <p>16/02/2009
 * @author Wenbo.Sun
 */
public class HibernateSessionFactory {

    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Configuration configuration = new AnnotationConfiguration();
    private static org.hibernate.SessionFactory sessionFactory;


//    static {
//        try {
//            sessionFactory = configuration.configure().buildSessionFactory();
//        } catch (Exception e) {
//            System.err.println("%%%% Error Creating SessionFactory %%%%");
//            e.printStackTrace();
//        }
//    }

    private HibernateSessionFactory() {
    }

    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);
        }

        return session;
    }

    public static void rebuildSessionFactory() {
        try {
            sessionFactory = configuration.configure().buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Configuration getConfiguration() {
        return configuration;
    }

    public static void addProperties (Properties pro) {
        configuration.addProperties(pro);
        rebuildSessionFactory();
    }
}